<template>
  <div class="home page" ref="calibrationTable">
    <!--搜索--START-->
    <div class="search-form border p-20-20-0-20 card-shadow">
      <auto-form :setting="searchFormSetting" :form="searchFormGroup" :button="searchFormButton"
                 :default-form="searchForm" @search="handleClickSearchFormSearch"
                 @export="handleClickSearchFormExport" @upload="handleClickAddRecord"
                 @delete="handleClickDeleteRecord" @plot="handlePlotSelect"/>
    </div>
    <!--搜索--END-->

    <!--列表--START-->
    <div class="list-table border p-20 m-20-0-0-0 card-shadow p-20-20-0-20">
      <auto-table is-checked :title="tableTitle" :data="mockTableData" :event="tableButton"
                  @checkRow="handleTableCheckRow" @edit="handleClickTableEdit" @delete="handleClickTableDelete"
                  @upload-result="handleClickUploadResult" @upload-params="handleClickUploadParams"
                  @upload-dataset="handleClickUploadDataset" @source-files="handleClickSourceFiles"
                  @export="handleClickExportMat"/>
      <!--分页-->
      <paging :total="pageTotal" :page="currentPage" :size="pageSize" @page="handleClickPage" @size="handleClickSize"/>
    </div>
    <!--列表--END-->

    <!--弹出层--START-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <auto-form v-if="dialogVisible" :setting="dialogFormSetting" :form="dialogFormGroup" :button="dialogFormButton"
                 :default-form="dialogForm" @update="handleClickDialogFormEdit" @create="handleClickDialogFormCreate"
                 @cancel="handleClickCancel"/>
    </el-dialog>
    <!--    上传文件-->
    <el-dialog :title="dialogTitle" :visible.sync="uploadVisible" width="30%">
      <auto-form v-if="uploadVisible" :setting="dialogFormSetting" :form="uploadResultFormGroup"
                 :button="uploadFormButton"
                 :default-form="dialogForm" @upload-result="handleClickFormUploadResult"
                 @upload-params="handleClickFormUploadParams" @upload-dataset="handleClickFormUploadDataset"
                 @download="handleClickFormDownFile" @download-all="handleClickFormDownAllFile"
                 @export-dataset="handleClickFormExportDataset"
                 @cancel="handleClickCancel"/>
    </el-dialog>
    <!--    弹出层&#45;&#45;END-->
  </div>
</template>

<script>
import autoForm from '@/views/data/calibration/components/autoForm/index.vue'
import autoTable from '@/views/data/calibration/components/autoTable/index.vue'
import autoTableMixins from '@/views/data/calibration/components/autoTable/mixins.js'
import paging from '@/views/data/calibration/components/paging/index.vue'
import {devServer} from '/vue.config.js'

import {
  searchFormSetting,
  searchFormGroup,
  searchFormButton,
  tableTitle,
  tableButton,
  dialogFormSetting,
  dialogFormGroup,
  dialogFormButton,
  uploadResultFormGroup,
  armOptions,
  handOptions
} from '@/views/data/calibration/index'
import axios from 'axios'

axios.defaults.baseURL = '/api'

const mockTableData = []
export default {
  name: 'index',
  title: '拉风的首页',
  components: {autoForm, autoTable, paging},
  mixins: [autoTableMixins],
  data() {
    return {
      // 搜索表单部分
      searchFormSetting,
      searchFormGroup,
      searchFormButton,
      searchForm: {},
      // 主体表格部分
      tableTitle,
      tableButton,
      mockTableData,
      // 弹出层
      dialogTitle: '弹出层标题',
      dialogVisible: false,
      uploadVisible: false,
      dialogFormSetting,
      dialogFormGroup,
      armOptions,
      handOptions,
      dialogFormButton,
      uploadResultFormGroup,
      uploadFormButton: {},
      dialogForm: {},
      // 分页
      pageTotal: mockTableData.length,
      currentPage: 1,
      pageSize: 20
    }
  },
  methods: {
    searchTableData() {
      axios.get('/calibration/search/', {
            params: {
              page: this.currentPage,
              page_size: this.pageSize,
              name: '',
              status: '',
              time: '',
              arm_id: '',
              robot_id: '',
              hand_id: '',
              console_id: '',
              type: '',
            }
          }
      ).then(
          response => {
            const responseData = JSON.parse(response.data)
            const tableList = [];
            responseData.records.forEach(item => {
              var tableItem = {
                "id": item.id,
                "name": item.name,
                "arm": item.arm_id,
                "robot": item.robot_id,
                "hand": item.hand_id,
                "console": item.console_id,
                "type": item.type,
                "start_time": item.start_time,
                "end_time": item.end_time,
                "time": [item.start_time, item.end_time],
                "result": item.result,
                "params": item.params,
                "source_data_path": item.source_data_path,
                "status": item.status,
                "worker": item.worker,
                "remarks": item.remarks,
                "create_at": item.create_at,
                "updated_at": item.updated_at
              };
              tableList.push(tableItem)
            })
            this.mockTableData = tableList;
            this.pageTotal = responseData.count;
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          })
    },
    // 当前页
    handleClickPage(count) {
      this.currentPage = count
      this.searchTableData();
    },
    // 每页条数
    handleClickSize(count) {
      this.pageSize = count
      this.searchTableData();
    },
    // 点击搜索表单搜索
    handleClickSearchFormSearch(form) {
      axios.get('/calibration/search/', {
            params: {
              page: 1,
              name: form.name,
              status: form.status,
              time: form.time,
              arm_id: form.arm,
              robot_id: form.robot,
              hand_id: form.hand,
              console_id: form.console,
              type: form.type,
            }
          }
      ).then(
          response => {
            const responseData = JSON.parse(response.data)
            const tableList = [];
            responseData.records.forEach(item => {
              var tableItem = {
                "id": item.id,
                "name": item.name,
                "arm": item.arm_id,
                "robot": item.robot_id,
                "hand": item.hand_id,
                "console": item.console_id,
                "type": item.type,
                "start_time": item.start_time,
                "end_time": item.end_time,
                "time": [item.start_time, item.end_time],
                "result": item.result,
                "params": item.params,
                "source_data_path": item.source_data_path,
                "status": item.status,
                "worker": item.worker,
                "remarks": item.remarks,
                "create_at": item.create_at,
                "updated_at": item.updated_at
              };
              tableList.push(tableItem)
            })
            this.mockTableData = tableList;
            this.pageTotal = responseData.count;
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          })
    },
    // 点击搜索表单重置【默认在子组件中处理过】
    // 点击搜索表单下载按钮【纯前端下载】
    handleClickSearchFormExport() {
      if (this.checkRow) {
        // 获取表格表头文字和属性
        // const tableHeader = tableTitle.map(i => i.label)
        // const tableProps = tableTitle.map(i => i.prop)
        // 勾选的的数据
        // const checkedData = this.checkRow
        // 取出勾选数据的value
        // const tableData = checkedData.map(v => tableProps.map(j => v[j]))
        // // 执行下载
        // exportExcel(tableHeader, tableData, 'autoTable')
        // 清空勾选的数据
        this.checkRow = null
      } else {
        this.$message({
          type: 'warning',
          message: '至少勾选一列'
        })
      }
    },
    // 列表勾选列【通用事件已经引入autoTableMixins, 页面直接使用this.checkRow】
    // 处理表格列编辑
    handleClickTableEdit(index, row) {
      this.dialogTitle = '编辑面板'
      this.dialogVisible = true
      this.dialogForm = row
      this.dialogFormButton = [
        {name: '确定', event: 'update', type: 'primary'},
        {name: '取消', event: 'cancel'}
      ]
    },
    // 点击上传结果
    handleClickUploadResult(index, row) {
      this.dialogTitle = '上传标定结果'
      this.uploadVisible = true
      this.dialogForm = row
      this.uploadResultFormGroup = [
        {label: '标定结果', type: 'textarea', readonly: true},
        {
          label: '结果上传',
          type: 'upload-drag',
          action: 'http://'+ devServer.public +'/api/calibration/upload/',
          limit: 1,
          tip: '请上传标定结果的MAT格式文件'
        }
      ]
      this.uploadFormButton = [
        {name: '上传到服务器', event: 'upload-result', type: 'success'},
        {name: '取消', event: 'cancel'}
      ]
      // this.dialogForm = row
    },
    // 点击上传标定参数
    handleClickUploadParams(index, row) {
      this.dialogTitle = '上传标定参数'
      this.uploadVisible = true
      this.dialogForm = row
      this.uploadResultFormGroup = [
        {label: '标定参数', type: 'textarea', readonly: true},
        {label: '结果上传', type: 'upload-drag', action: 'http://'+ devServer.public +'/api/calibration/upload/', limit: 1,
        tip: '请上传标定参数的MAT格式文件'}
      ]
      this.uploadFormButton = [
        {name: '上传到服务器', event: 'upload-params', type: 'success'},
        {name: '取消', event: 'cancel'}
      ]
      // this.dialogForm = row
    },
    // 点击上传关节角度数据集
    handleClickUploadDataset(index, row) {
      this.dialogTitle = '上传标定数据'
      this.uploadVisible = true
      this.dialogForm = row
      this.uploadResultFormGroup = [
        {label: '标定数据', type: 'textarea', readonly: true},
        {
          label: '光学数据',
          type: 'upload-drag',
          action: 'http://' + devServer.public + '/api/calibration/upload/',
          tip: '请上传光学C-Track xls 数据',
          limit: 20
        },
        {
          label: '编码器数据',
          type: 'upload-file',
          action: 'http://' + devServer.public + '/api/calibration/upload/',
          tip: '请上传上位机到处的编码器关节角度 xls 数据',
          limit: 1
        }
      ]
      this.uploadFormButton = [
        {name: '上传到服务器', event: 'upload-dataset', type: 'success'},
        {name: '取消', event: 'cancel'}
      ]
    },
    handleClickExportMat(index, row) {
      this.dialogTitle = '导出数据集MAT'
      this.uploadVisible = true
      this.dialogForm = row
      if (row.type === 'ROBOT') {
        this.uploadResultFormGroup = [
          {label: '机械臂', type: 'select', required: true, kind: 'ROBOT', options: armOptions}
        ]
      } else if(row.type === 'CONSOLE') {
        this.uploadResultFormGroup = [
          {label: '主手', type: 'select', required: true, kind: 'ROBOT', options: handOptions}
        ]
      }
      this.uploadFormButton = [
        {name: '导出', event: 'export-dataset', type: 'success'},
        {name: '取消', event: 'cancel'}
      ]
    },
    handleClickSourceFiles(index, row) {
      axios.get('/calibration/source/data/', {
        params: {
          id: row.id
        }
      }).then(
          response => {
            this.dialogTitle = '原始数据'
            this.uploadVisible = true
            row['source_data_files'] = JSON.parse(response.data).data
            this.dialogForm = row
            this.uploadResultFormGroup = [
              {
                label: '文件列表',
                type: 'download',
                event: 'download'
              }
            ]
            this.uploadFormButton = [
              {name: '下载全部', event: 'download-all', type: 'success'},
            ]
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          });
    },
    // 点击添加记录
    handleClickAddRecord() {
      this.dialogTitle = '添加标定记录'
      this.dialogVisible = true
      this.dialogFormButton = [
        {name: '确定', event: 'create', type: 'primary'},
        {name: '取消', event: 'cancel'}
      ]
      // this.dialogForm = row
    },
    // 处理批量删除
    handleClickDeleteRecord() {
      if (this.checkRow) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const id_list = [];
          this.checkRow.forEach(item => {
            id_list.push(item.id);
          });
          axios.delete('/calibration/delete/selects/', {
            params: {
              ids: id_list
            }
          }).then(
              response => {
                this.$message({
                  message: response.data.message,
                  type: 'success',
                  showClose: true
                })
                // 清空勾选的数据
                this.checkRow = null
                this.searchTableData()
              },
              // 失败
              error => {
                this.$message.error({message: error.response.data.message, showClose: true});
              })
          // location.reload()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.$message({
          type: 'warning',
          message: '至少勾选一列'
        })
      }
    },
    // 处理表格列删除
    handleClickTableDelete(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/calibration/delete/', {
          params: {
            id: row.id
          }
        }).then(
            response => {
              this.$message({
                message: response.data.message,
                type: 'success',
                showClose: true
              })
              this.searchTableData();
            },
            // 失败
            error => {
              this.$message.error({message: error.response.data.message, showClose: true});
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 处理弹出层表单编辑
    handleClickDialogFormEdit(form) {
      axios.post('/calibration/update/', form).then(
          response => {
            this.dialogVisible = false;
            this.searchTableData();
            this.$message({
              message: response.data.message,
              type: 'success',
              showClose: true
            });
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          });
    },
    // 处理表单对话创建
    handleClickDialogFormCreate(form) {
      axios.post('/calibration/create/', form).then(
          response => {
            this.dialogVisible = false;
            this.searchTableData();
            this.$message({
              message: response.data.message,
              type: 'success',
              showClose: true
            });
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          });
    },
    // 处理标定关节角度数据上传
    handleClickFormUploadDataset(form) {
      if (form.file_list.length > 0) {
        axios.post('/calibration/dataset/bind/', form).then(
            response => {
              this.uploadVisible = false;
              this.searchTableData();
              this.$message({
                message: response.data.message,
                type: 'success',
                showClose: true
              });
            },
            // 失败
            error => {
              this.$message.error({message: error.response.data.message, showClose: true});
            });
      } else {
        this.$message({message: "未上传文件", showClose: true, type: 'warning'});
      }
    },
    // 处理标定参数上传服务器
    handleClickFormUploadParams(form) {
      if (form.file_list.length > 0) {
        axios.post('/calibration/params/bind/', form).then(
            response => {
              this.uploadVisible = false;
              this.searchTableData();
              this.$message({
                message: response.data.message,
                type: 'success',
                showClose: true
              });
            },
            // 失败
            error => {
              this.$message.error({message: error.response.data.message, showClose: true});
            });

       } else {
        this.$message({message: "未上传文件", showClose: true, type: 'warning'});
      }
    },
    // 处理标定结果上传服务器
    handleClickFormUploadResult(form) {
      if (form.file_list.length > 0) {
        axios.post('/calibration/result/bind/', form).then(
            response => {
              this.uploadVisible = false;
              this.searchTableData();
              this.$message({
                message: response.data.message,
                type: 'success',
                showClose: true
              });
            },
            // 失败
            error => {
              this.$message.error({message: error.response.data.message, showClose: true});
            });
      } else {
        this.$message({message: "未上传文件", showClose: true, type: 'warning'});
      }
    },
    // 下载源文件
    download (response) {
        if (!response) {
            return
        }
        let url = window.URL.createObjectURL(new Blob([response.data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        let filename = response.headers['content-disposition'].split("=")[1]
        link.setAttribute('download', filename)
        document.body.appendChild(link)
        link.click()
    },
    handleClickFormDownFile(form) {
      axios({
        method: 'post',
        url: '/calibration/source/download/',
        data: form,
        responseType: 'blob'
      }).then(response => {
        response['filename'] = form.name
        this.download(response)
      }).catch((error) => {
        this.$message.error({message: error.response.data.message, showClose: true});
      })
    },
    handleClickFormDownAllFile(form) {
      if (form.source_data_files.length === 0) {
        this.$message({message: "啥文件都没有你点个毛线下载！", showClose: true, type: 'warning'});
      } else {
        axios({
          method: 'post',
          url: '/calibration/source/all/',
          params: {id: form.id},
          responseType: 'blob'
        }).then(response => {
          this.download(response)
        }).catch((error) => {
          this.$message.error({message: error.response.data.message, showClose: true});
        })
      }
    },
    // 导出mat功能
    handleClickFormExportDataset(form) {
      axios({
        method: 'post',
        url: '/calibration/dataset/export/mat/',
        params: {
          id: form.id,
          type: form.type,
          hand_id: form.hand,
          arm_id: form.arm
        },
        responseType: 'blob'
      }).then(response => {
        this.download(response)
      }).catch((error) => {
        this.$message.error({message: error.response.data.message, showClose: true});
      })
    },
    handleClickCancel() {
      this.uploadVisible = false
      this.dialogVisible = false
    },
    handlePlotSelect() {
      if (this.checkRow) {
        this.$router.push({name: "数据可视化", params: {rows: this.checkRow}})
      } else {
        this.$message({
          type: 'warning',
          message: '至少勾选一列'
        })
      }
    }
  },
  mounted() {
    this.searchTableData()
  }
}
</script>

<style scoped lang="scss">

</style>
